// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import ElementUI from 'element-ui';
// import 'element-ui/lib/theme-chalk/index.css';
import './assets/css/element-variables.scss'
import App from './App'
import router from './router'
import axios from 'axios';
import store from './store';
import VueAxios from 'vue-axios';
import Qs from 'qs';
// el 弹窗可拖拽
import './assets/js/move_dialog'
// el 表格横向滚动条 可拖拽
import './assets/js/tableDrag'


Vue.config.productionTip = false
Vue.use(ElementUI, { size: 'small'});

Vue.prototype.file_http='https://pg.gcbhshop.com/'

import FormItem from './components/FormItem/index.vue';
import Pagination from "@/components/Pagination";


import Nodata from "@/components/Nodata";
// 表单元素
Vue.component('FormItem', FormItem);
Vue.component('Pagination', Pagination);

Vue.component('Nodata', Nodata)

Vue.prototype.tip_show=function(msg,status){
  this.$message({
    message: msg,
    type: status
  });
}
Vue.prototype.get_th_img=function(img_url){
  if(img_url.indexOf('aliyuncs.com')==-1){
    return img_url
  }else{
    if(img_url.indexOf('x-oss-process=image')==-1){
      return img_url+'?x-oss-process=image/resize,w_200,m_lfit'
    }else{
      return img_url+'/resize,w_200,m_lfit'
    }
  }
}


// 时间戳转化成 对应的时间格式
Vue.prototype.getMyDate=function(str, _type) {
  var oDate = new Date(str),
    oYear = oDate.getFullYear(),
    oMonth = oDate.getMonth() + 1,
    oDay = oDate.getDate(),
    oHour = oDate.getHours(),
    oMin = oDate.getMinutes(),
    oSen = oDate.getSeconds();
  //  格式 13:12
  if (_type == 'time_h_m') {
    var oTime = getzf(oHour) + ':' + getzf(oMin)
  }
  if (_type == 'time_h_ms') {

    var _times = getzf(oMin).toString()[0] + '0'
    var oTime = getzf(oHour) + ':' + _times
  }
  // 格式 13:12:25
  if (_type == 'time_h_m_s') {
    var oTime = getzf(oHour) + ':' + getzf(oMin) + ':' + getzf(oSen);
  }
  // 格式 2017-12-12
  if (_type == 'year') {
    var oTime = oYear + '-' + getzf(oMonth) + '-' + getzf(oDay)
  }
  // 格式 2017-12
  if (_type == 'year_m') {
    var oTime = oYear + '-' + getzf(oMonth)
  }
  // 格式 2017-12-12 13:12:25
  if (_type == 'year_time') {
    var oTime = oYear + '-' + getzf(oMonth) + '-' + getzf(oDay) + ' ' + getzf(oHour) + ':' + getzf(oMin) + ':' + getzf(oSen);//最后拼接时间
  }
  // 需要更多格式可再自定义
  return oTime;

  //补0操作
  function getzf(num) {
    if (parseInt(num) < 10) {
      num = '0' + num;
    }
    return num;
  }
}
Vue.prototype.strtotime=function(str) {
  var _arr = str.split(' ');
  var _day = _arr[0].split('-');
  _arr[1] = (_arr[1] == null) ? '0:0:0' : _arr[1];
  var _time = _arr[1].split(':');
  for (var i = _day.length - 1; i >= 0; i--) {
    _day[i] = isNaN(parseInt(_day[i])) ? 0 : parseInt(_day[i]);
  };
  for (var i = _time.length - 1; i >= 0; i--) {
    _time[i] = isNaN(parseInt(_time[i])) ? 0 : parseInt(_time[i]);
  };
  var _temp = new Date(_day[0], _day[1] - 1, _day[2], _time[0], _time[1], _time[2]);
  return _temp.getTime();
}
Vue.prototype.get_prev_montn=function(){
    let now = new Date();
    // 当前月的日期
    let nowDate = now.getDate();
    let lastMonth = new Date(now.getTime());
    // 设置上一个月（这里不需要减1）
    lastMonth.setMonth(lastMonth.getMonth());
    // 设置为0，默认为当前月的最后一天
    lastMonth.setDate(0);
    // 上一个月的天数
    let daysOflastMonth = lastMonth.getDate();
    // 设置上一个月的日期，如果当前月的日期大于上个月的总天数，则为最后一天
    lastMonth.setDate(nowDate > daysOflastMonth ? daysOflastMonth : nowDate);
    return Vue.prototype.getMyDate(Date.parse(lastMonth),'year');
}


Vue.prototype.get_enter_url=function(menus,url){
  if(url=='/notFound'){
    return false
  }else{
    if(url){
      if(Vue.prototype.have_auth(url)){
        return false
      }else{
        return find_enter()
      }
    }else{
      return find_enter()
    }
  }
  function find_enter(){
    let urls=['/','/project/index','/answer/index','/institution/index','/policy_management/policy/index','/dictionary/type','/dictionary/policy-category','/system/index','/system/menu','/system/user','/system/role'];

    let find_url='';
    for(let i=0;i<urls.length;i++){
        if(Vue.prototype.have_auth(urls[i])){
          find_url= urls[i];
          break;
        }
    }
    if(find_url){
      return find_url
    }else{
      return '/notFound'
    }
  }
}
Vue.prototype.have_auth=function(url){
    let n=0;
    for(let i=0;i<store.state.menu.length;i++){
      // console.log(url,store.state.menu[i])
        if(url==store.state.menu[i]){
            n++
            break;
        }
    }
    return n>0?true:false
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
Vue.prototype.handleTree=function(data, id, parentId, children) {
	let config = {
		id: id || 'id',
		parentId: parentId || 'parentId',
		childrenList: children || 'children'
	};

	var childrenListMap = {};
	var nodeIds = {};
	var tree = [];

	for (let d of data) {
		let parentId = d[config.parentId];
		if (childrenListMap[parentId] == null) {
			childrenListMap[parentId] = [];
		}
		nodeIds[d[config.id]] = d;
		childrenListMap[parentId].push(d);
	}

	for (let d of data) {
		let parentId = d[config.parentId];
		if (nodeIds[parentId] == null) {
			tree.push(d);
		}
	}

	for (let t of tree) {
		adaptToChildrenList(t);
	}

	function adaptToChildrenList(o) {
		if (childrenListMap[o[config.id]] !== null) {
			o[config.childrenList] = childrenListMap[o[config.id]];
		}
		if (o[config.childrenList]) {
			for (let c of o[config.childrenList]) {
				adaptToChildrenList(c);
			}
		}
	}
	return tree;
}


// key:value  转 select 可用的 格式  {'1':'选项1','2':'选项2'}==>   [{'label':'选项1','value':'1'},{'label':'选项2','value':'2'}]
Vue.prototype.obj2arr=function(option){
  let options=[];
  for(let item in option){
    options.push({label:option[item],value:item})
  }
  return options
};

// 状态管理
Vue.prototype.getState = function() {
  var _data = localStorage.pingguUserinfo;

  if (_data) {
    return JSON.parse(_data)
  } else {
    return {
      id: '',
      token:''
    }
  }
}



Vue.prototype.setState = function(_data) {
  localStorage.pingguUserinfo = JSON.stringify(_data)
}

Vue.prototype.resetForm=function(refName) {
	if (this.$refs[refName]) {
		this.$refs[refName].resetFields();
	}
}
let $http='';
if(process.env.NODE_ENV=="development"){$http='/myapi'; }
Vue.prototype.http=$http

Vue.use(VueAxios, axios);
Vue.config.productionTip = false



// 去掉文章内容页的路径
Vue.prototype.remove_upload_http=function(content){
  let base='src="'+$http+'/storage/';
  let reg=new RegExp(base,'g');
	return content.replace(reg, 'src="')
};
// 添加上文章内容页的 路径
Vue.prototype.add_upload_http=function(content){
  let base=$http+'/storage/';
  let src='src="temp';
  let reg=new RegExp(src,'g');
	return content.replace(reg, 'src="'+base+'temp')
};


Vue.prototype.setheader = function() {
  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  axios.defaults.headers.post['user-authorization'] =Vue.prototype.getState().token?Vue.prototype.getState().token:'';
  axios.defaults.headers.get['user-authorization'] =Vue.prototype.getState().token?Vue.prototype.getState().token:'';
}

Vue.prototype.setheader();

axios.interceptors.request.use(function(config) {
  config.url=$http+config.url
  // 在发送请求之前做些什么
  // 使用qs对参数进行处理
  config.data = Qs.stringify(config.data);
  // console.log(config)
  return config
}, function(error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})


axios.interceptors.response.use(
 response => {
  // token失效重新启动
  if(response.data.status==401 || response.data.status==403){
    Vue.prototype.setState('');
    Vue.prototype.setheader();
    router.replace({path:'/login'});
    return false;
  }else if(response.data.status==200){
    return response.data
  }else{
    Vue.prototype.tip_show(response.data.msg || response.data.message,'error')
    return false;
  }
 },
 error => {
  return Promise.reject(error)
 }
)
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})
